package com.itany.nmms.controller;

import com.itany.mvc.annotation.RequestMapping;
import com.itany.nmms.entity.Staff;
import com.itany.nmms.exception.CodeErrorException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.exception.StaffNotExistException;
import com.itany.nmms.factory.ObjectFactory;
import com.itany.nmms.service.StaffService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石小俊
 * @date 2023年07月21日 15:37
 */
@RequestMapping("/staff")
public class StaffController {

    private StaffService staffService = (StaffService) ObjectFactory.getObject("staffService");

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response){
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        String role = request.getParameter("role");
        String code = request.getParameter("code");
        String image = (String) request.getSession().getAttribute("code");

        try {
            Staff staff = staffService.login(loginName,password,role,code,image);
            request.getSession().setAttribute("staff",staff);

            // 对于方法返回值有三种格式
            // 1.redirect:url   使用重定向跳转到指定url地址
            // 2.url            使用转发跳转到指定url地址
            // 3.视图名          使用转发访问指定的视图
                // 此时的视图也需要经过DispatcherServlet处理
                // 最终访问的jsp为:prefix+视图名+suffix
            return "redirect:/showMain.do";
        } catch (RequestParameterErrorException e) {
            request.setAttribute("staffMsg",e.getMessage());
            return "/showLogin.do";
        } catch (CodeErrorException e) {
            request.setAttribute("staffMsg",e.getMessage());
            return "/backend/login";
        } catch (StaffNotExistException e) {
            request.setAttribute("staffMsg",e.getMessage());
            return "/backend/login";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("staffMsg","服务器内部异常");
            return "/backend/login";
        }

    }

}
